package com.woniuxy.controller;

import com.woniuxy.entity.CommonResult;
import com.woniuxy.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: linKe
 * @Date: 2021/12/28 19:20
 * @FileName: UserRibbonController
 * @version: 1.0
 * @Description: 用户动态均衡控制器测试访问
 */
@Log4j2
@RestController
@RequestMapping("/user")
public class UserRibbonController {
    /**注入RestTemplate，使用其调用user-service中提供的相关接口*/
    @Autowired
    private RestTemplate restTemplate;
    /**读取配置文件调用的服务名*/
    @Value("${service-url.user-service}")
    private String userServiceUrl;

    @GetMapping("/{id}")
    public CommonResult<?> getUser(@PathVariable Long id) {
        //使用restTemplate http请求调用
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    @GetMapping("/getByUsername")
    public CommonResult<?> getByUsername(@RequestParam String username) {
        return restTemplate.getForObject(userServiceUrl + "/user/getByUsername?username={1}", CommonResult.class, username);
    }

    @GetMapping("/getEntityByUsername")
    public CommonResult<?> getEntityByUsername(@RequestParam String username) {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(userServiceUrl + "/user/getByUsername?username={1}", CommonResult.class, username);
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        } else {
            return new CommonResult<>("操作失败", 500);
        }
    }

    @PostMapping("/create")
    public CommonResult<?> create(@RequestBody User user) {
        return restTemplate.postForObject(userServiceUrl + "/user/create", user, CommonResult.class);
    }

    @PostMapping("/update")
    public CommonResult<?> update(@RequestBody User user) {
        return restTemplate.postForObject(userServiceUrl + "/user/update", user, CommonResult.class);
    }

    @PostMapping("/delete/{id}")
    public CommonResult<?> delete(@PathVariable Long id) {
        return restTemplate.postForObject(userServiceUrl + "/user/delete/{1}", null, CommonResult.class, id);
    }
}
